/*
 * Copyright 2014 mobiao.inc. All right reserved.
 * 
 * path: 
 * author: sagyf yang
 * version: 1.0.0
 * date: 2/8/15 17:07
 */
define(function (require, exports, module) {

    var tree_btn_tpl = require('hbs!./common/tree_btn');

    return {
        init: function () {

            var newCount = 0;

            var tree_dom = 'dict_tree';

            function addHoverDom(treeId, treeNode) {
                if(treeNode.data['sys_flag'] == 'Y'){
                    return false;
                }
                var sObj = $("#" + treeNode.tId + "_span");
                var $add_btn = $("#addBtn_" + treeNode.tId);
                if (treeNode.editNameFlag || $add_btn.length > 0) return;
                var btn_html = tree_btn_tpl({id: treeNode.tId });
                sObj.after(btn_html);
                var add_btn = $("#addBtn_" + treeNode.tId);
                if (add_btn) add_btn.bind("click", function () {
                    var zTree = $.fn.zTree.getZTreeObj(tree_dom);
                    var new_name = "新字典" + (newCount++);
                    var new_node = zTree.addNodes(treeNode, {id: (100 + newCount), pId: treeNode.id, name: new_name,
                        'data': {id: 0, code: newCount + 'code', name: new_name, parent: treeNode.id, 'sort': 1}});
                    if (new_node) {
                        initFormData(new_node[0]['data']);
                        zTree.selectNode(new_node[0]);
                    }

                    return false;
                });
                var remove_btn = $('#removeBtn_' + treeNode.tId);
                if (remove_btn) remove_btn.bind('click', function () {
                    var zTree = $.fn.zTree.getZTreeObj(tree_dom),
                        nodes = zTree.getSelectedNodes();
                    if (nodes.length == 0) {
                        return;
                    }
                    var treeNode = nodes[0];
                    zTree.removeNode(treeNode, true);

                });
            }


            function initFormData(node_data){
                $('#id').val(node_data['id']);
                $('#parent').val(node_data['parent']);
                $('#code').val(node_data['code']);
                $('#name').val(node_data['name']);
                $('#sort').val(node_data['sort']);
                $('#chinese_name').val(node_data['chinese_name']);
            }

            function removeHoverDom(treeId, treeNode) {
                if(treeNode.data['sys_flag'] == 'Y'){
                    return false;
                }
                $("#addBtn_" + treeNode.tId).unbind().remove();
                $("#removeBtn_" + treeNode.tId).unbind().remove();
            }

            var _data_filter = function (treeId, parentNode, childNodes) {
                if (!childNodes) return null;
                for (var i = 0, l = childNodes.length; i < l; i++) {
                    childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
                }
                return childNodes;

            };
            var setting = {
                check: {
                    enable: false
                },
                view: {
                    addHoverDom: addHoverDom,
                    removeHoverDom: removeHoverDom,
                    dblClickExpand: false,
                    showLine: true,
                    selectedMulti: false
                },
                async: {
                    enable: true,
                    url: g.ctx + 'baseinfo/dict/nodes',
                    autoParam: ["id"],
                    dataFilter: _data_filter
                },
                callback: {
                    beforeRemove: beforeRemove,
                    onClick: click_node
                }
            };

            function click_node(event, treeId, treeNode) {
                initFormData(treeNode['data']);
                return false;
            }

            function beforeRemove(treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj(tree_dom);
                zTree.selectNode(treeNode);
                var res = false;
                bootbox.confirm("您确认要删除:字典 " + treeNode.data.name + " 吗？", function (result) {
                    if (result) {
                        var data = treeNode.data;
                        if (data['id']) {
                            $.post(g.ctx + 'baseinfo/dict/delete/' + data.id, function (rst) {
                                if (rst.status === 'OK') {
                                    zTree.removeNode(treeNode);
                                    $('#dict_form')[0].reset();
                                } else {

                                }
                            });
                        } else {
                            zTree.removeNode(treeNode);
                        }
                    }
                });
                return res;
            }


            $.fn.zTree.init($("#dict_tree"), setting);

            $('#dict_form').ajaxForm({
                success: function (responseText, statusText) {
                    if (responseText.status === 'OK') {
                        var zTree = $.fn.zTree.getZTreeObj('dict_tree');
                        var nodes = zTree.getSelectedNodes();
                        if (nodes.length == 0) {
                            // 刷新根节点
                            zTree.reAsyncChildNodes(null, 'refresh');
                        } else {
                            var node = nodes[0];
                            node.name = responseText.data['name'];
                            node.data = responseText.data;
                            zTree.updateNode(node);
                        }

                        $('#dict_form')[0].reset();

                        bootbox.alert('设置字典成功');
                    } else {
                        bootbox.alert(responseText.message);
                    }
                },
                dataType: 'json'
            });

        }
    };
});